package com.baitiaojun.video.handler.canal.comment;

import com.baitiaojun.api.domain.video.VideoChildComment;
import com.baitiaojun.api.domain.video.VideoComment;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.vo.JsonRes;
import com.baitiaojun.video.feign.ElasticsearchVideoFeign;
import com.baitiaojun.video.handler.canal.SyncEsHandler;
import lombok.SneakyThrows;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * @类名 CommentCountSyncEsHandler
 * @作者 白条君
 * @创建日期 2023/1/25 01:54
 * @版本 1.0
 */
@Component
@CanalTable("t_video_comment")
public class VideoCommentSyncEsHandler extends SyncEsHandler implements EntryHandler<VideoComment> {

    @Autowired
    private ElasticsearchVideoFeign elasticsearchVideoFeignFeign;

    @SneakyThrows
    @Override
    public void insert(VideoComment videoComment) {
        Long videoId = videoComment.getVideoId();
        //添加视频评论到es
        Long replyUserId = videoComment.getReplyUserId();
        Long rootId = videoComment.getRootId();
        if (ObjectUtils.isNotEmpty(replyUserId) && ObjectUtils.isNotEmpty(rootId)) {
            VideoChildComment videoChildComment = new VideoChildComment();
            videoChildComment.setId(videoComment.getId());
            videoChildComment.setUserid(videoComment.getUserId());
            videoChildComment.setReplyuserid(replyUserId);
            videoChildComment.setRootid(rootId);
            videoChildComment.setVideoid(videoId);
            videoChildComment.setComment(videoComment.getComment());
            videoChildComment.setCreatetime(videoComment.getCreateTime());
            JsonRes jsonRes = elasticsearchVideoFeignFeign.saveChildVideoComment(videoChildComment);
            if (jsonRes.get("status").equals(500)) {
                throw new ConditionException("二级评论添加到es失败");
            }
        } else {
            JsonRes jsonRes = elasticsearchVideoFeignFeign.saveVideoComment(videoComment);
            if (jsonRes.get("status").equals(500)) {
                throw new ConditionException("一级评论添加到es失败");
                //更新视频评论数
            }
            super.updateVideo(videoId);
        }
    }

    @SneakyThrows
    @Override
    public void delete(VideoComment videoComment) {
        //移除视频评论es
        Long replyUserId = videoComment.getReplyUserId();
        Long rootId = videoComment.getRootId();
        if (ObjectUtils.isNotEmpty(replyUserId) && ObjectUtils.isNotEmpty(rootId)) {
            elasticsearchVideoFeignFeign.removeVideoChildComment(videoComment.getId());
        } else {
            elasticsearchVideoFeignFeign.removeVideoComment(videoComment.getId());
            //更新视频评论数
            super.updateVideo(videoComment.getVideoId());
        }
    }
}
